package demo3;

import java.util.Arrays;

/**
 * 堆排序
 * 1、树要是完全二叉树
 * 2、parent > children (大顶堆) 或 parent < children (小顶堆)
 */
public class HeapSortTest {
    public static void main(String[] args) {
        int[] arr = new int[]{4,1,90,45,2,48,52,13,7,5,25,2};
        heapSort(arr,arr.length-1);
        System.out.println(Arrays.toString(arr));
    }

    public static void heapSort(int[] arr,int lastIndex){

        // 迭代终止条件
        if(lastIndex <= 0) return;

        // 1. 从最后一个非叶子节点开始向前构建大顶堆
        for (int i = (lastIndex-1)/2; i >= 0 ; i--) {
            adjustMaxHeap(arr,i,lastIndex);
        }

        // 2、把首位的交换至后一位
        swap(arr,0,lastIndex);

        // 3、迭代
        heapSort(arr,lastIndex-1);
    }

    // 构建大顶堆
    private static void adjustMaxHeap(int[] arr, int i,int lastIndex) {
        int max = arr[i];
        if(2*i+1 <= lastIndex && arr[2*i+1] > max){
            swap(arr,i,2*i+1);
        }
        if(2*i+2 <= lastIndex && arr[2*i+2] > max){
            swap(arr,i,2*i+2);
        }
    }

     // 构建小顶堆
    private static void adjustMinHeap(int[] arr, int i,int lastIndex) {
        int max = arr[i];
        if(2*i+1 <= lastIndex && arr[2*i+1] < max){
            swap(arr,i,2*i+1);
        }
        if(2*i+2 <= lastIndex && arr[2*i+2] < max){
            swap(arr,i,2*i+2);
        }
    }

    // 交换数组中两个位置上的元素
    public static void swap(int[] arr,int i,int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
